/**
 * 简化的合并功能Hook
 * 只提供基础的手动合并和拆分功能，去掉复杂的智能检测
 */

import { useState, useCallback } from 'react';
import { RoomStatus } from '../../../types/room';
import type { Room, RoomAvailability } from '../../../types/room';

// 简化的合并块接口
export interface SimpleMergedBlock {
  id: string;
  roomId: string;
  startDate: string;
  endDate: string;
  dates: string[];
  status: RoomStatus;
  guestName?: string; // 客人姓名
  note?: string; // 备注信息
}

export const useSimpleMerge = () => {
  const [mergedBlocks, setMergedBlocks] = useState<SimpleMergedBlock[]>([]);

  // 手动合并选中的单元格
  const mergeSelectedCells = useCallback(
    (
      selectedCells: { roomId: string; date: string }[],
      guestName?: string,
      note?: string
    ) => {
      if (selectedCells.length < 2) return false;

      // 按房间分组
      const cellsByRoom = selectedCells.reduce(
        (acc, cell) => {
          if (!acc[cell.roomId]) acc[cell.roomId] = [];
          acc[cell.roomId].push(cell.date);
          return acc;
        },
        {} as Record<string, string[]>
      );

      const newBlocks: SimpleMergedBlock[] = [];

      Object.entries(cellsByRoom).forEach(([roomId, dates]) => {
        if (dates.length < 2) return;

        // 排序日期
        const sortedDates = dates.sort();

        const block: SimpleMergedBlock = {
          id: `merged-${roomId}-${Date.now()}`,
          roomId,
          startDate: sortedDates[0],
          endDate: sortedDates[sortedDates.length - 1],
          dates: sortedDates,
          status: RoomStatus.BOOKED, // 默认为预订状态
          guestName,
          note,
        };

        newBlocks.push(block);
      });

      if (newBlocks.length > 0) {
        setMergedBlocks(prev => [...prev, ...newBlocks]);
        return true;
      }

      return false;
    },
    []
  );

  // 拆分合并块
  const splitMergedBlock = useCallback((blockId: string) => {
    setMergedBlocks(prev => prev.filter(block => block.id !== blockId));
    return true;
  }, []);

  // 更新合并块信息
  const updateMergedBlock = useCallback(
    (
      blockId: string,
      updates: Partial<Pick<SimpleMergedBlock, 'guestName' | 'note' | 'status'>>
    ) => {
      setMergedBlocks(prev =>
        prev.map(block =>
          block.id === blockId ? { ...block, ...updates } : block
        )
      );
    },
    []
  );

  // 检查单元格是否在合并块中
  const getMergeBlockForCell = useCallback(
    (roomId: string, date: string) => {
      return mergedBlocks.find(
        block => block.roomId === roomId && block.dates.includes(date)
      );
    },
    [mergedBlocks]
  );

  // 获取合并统计
  const getStats = useCallback(() => {
    return {
      totalBlocks: mergedBlocks.length,
      totalDays: mergedBlocks.reduce(
        (sum, block) => sum + block.dates.length,
        0
      ),
      savedCells: mergedBlocks.reduce(
        (sum, block) => sum + (block.dates.length - 1),
        0
      ),
    };
  }, [mergedBlocks]);

  // 清空所有合并块
  const clearAllMerges = useCallback(() => {
    setMergedBlocks([]);
  }, []);

  return {
    // 状态
    mergedBlocks,

    // 操作函数
    mergeSelectedCells,
    splitMergedBlock,
    updateMergedBlock,
    getMergeBlockForCell,
    getStats,
    clearAllMerges,
  };
};

export default useSimpleMerge;
